<?php

namespace App\Admin\Controllers;

use App\Models\Category;
use App\Models\ProductSku;
use App\Models\ProductSpec;
use App\Models\ProductSpecItem;
use App\Models\Product;
use App\Http\Controllers\Controller;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Api\Traits\Responder;

class ProductsController extends Controller
{
    use HasResourceActions,Responder;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('商品列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed   $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('商品')
            ->description('列表')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑商品')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('创建商品')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Product);
        $grid->id('ID')->sortable();
        $grid->title('商品名称');
        $states = [
            'on'  => ['value' => 1, 'text' => '上架', 'color' => 'primary'],
            'off' => ['value' => 0, 'text' => '下架', 'color' => 'default'],
        ];
        $grid->column('on_sale','上架')->switch($states);
        $grid->price('最低价');
        $grid->sold_count('销量');
        $grid->actions(function ($actions) {
            $actions->disableView();
            $actions->disableDelete();
            $id = $actions->getKey();
            $actions->append('<a href="/admin/products/spec?goods_id='.$id.'" title="规格" style="padding-left: 5px"><i class="fa fa-flickr"></i></a>');
        });
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        $grid->disableExport();
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->like('title', '产品名称');
            $filter->equal('category_id','分类名称')->select(Category::where(['isshow'=>1])
                ->get()->pluck('name', 'id'));
            $filter->equal('on_sale','上架')->radio([
                0    => '下架',
                1    => '上架',
            ]);
            $filter->between('created_at', '添加时间')->datetime();
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Product::findOrFail($id));

        $show->id('ID');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Product);
        $form->text('title', '商品名称')
            ->rules('required');
        $form->text('weight', '重量/kg')
            ->rules('required');
        $form->number('sold_count', '销量')->default(0);
        $form->image('image', '封面图片')
            ->move('products')->name(function($file){
            return uniqid().'.'.$file->guessExtension();
        });
        $form->multipleImage('img_group','多图展示')
            ->move('products_show')->removable();
        $form->UEditor('description', '商品描述')->rules('required');
        $states = [
            'on'  => ['value' => 1, 'text' => '上架', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '下架', 'color' => 'danger'],
        ];
        $form->switch('on_sale','上架')->states($states)->default(1);
        //$form->tags('refund_tag', '退款规则');
        return $form;
    }


    /*
     * 规格
     */
    public function spec(Content $content, Request $request)
    {
        (new Admin)->disablePjax();
        Admin::js('/vendor/sku/js/vue.js');
        Admin::js('/vendor/sku/js/element.js');
        Admin::js('/vendor/sku/js/axios.js');
        Admin::css('/vendor/sku/css/element.css');
        Admin::css('/vendor/sku/css/home.css');
        $vue = <<<EOF
        const app = new Vue({
		el: "#app",
		data: {
			num: 0,
			goods_id:'' ,
			imageUrl: '',
			dialogImageUrl: '',
			dialogVisible: false,
			nav: [{ 
				name: '库存',
				prop: 'kucun'
			    },
				{
					name: '销售价',
					prop: 'yushoujia'
				},
				{
					name: '代理价',
					prop: 'vipprice'
				},
				{
					name: '京东EMG编码',
					prop: 'EMGcode'
				},
			],//属性变动需要改
			guige: [

			],
			tableData: [],
			loading_ac: '',
			guding_item: [],
			index: '', //当前操作的guige index
			idx: '' //当前操作的规格里的 list的index
		},
		methods: {
			send() {
				if (this.tableData.length == 0) {
					return this.\$alert('您还没有生成表格!', '提示', {
						confirmButtonText: '确定',
					});
				}
				this.loading()
				axios.post('/admin/goods/skus', {
					goods_id: this.goods_id,
					sku: this.tableData,
					spec: this.guige
				}).then(res => {
					this.loading_ac.close();
					if (res.data.code == 1) {
						this.\$alert(res.data.msg, '提示', {
							confirmButtonText: '确定',
							callback: action => {
                                window.location.href = '/admin/products';
                            }
						});
					}
				})
			},
			loading() {
				this.loading_ac = this.\$loading({
					lock: true,
					text: 'Loading',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
			},
			handleAvatarSuccess(res, file) {
				this.guige[this.index].list[this.idx].thumb = res.path
				this.loading_ac.close();
			},
			shangchuan(k, k9) {
				this.index = k
				this.idx = k9
			},
			//添加规格项
			addItem(idx, title) {
				if (!this.guige[idx].title) {
					return this.\$alert('您的规格为空!,所以无法添加规格项', '提示', {
						confirmButtonText: '确定',
					});
				}
				var reg = /^[\u4E00-\u9FA5]+$/;
				if (!reg.test(title)) {
					return this.\$alert('请输入中文', '提示', {
						confirmButtonText: '确定',
					});
				}
				let t = {
					name: '',
					thumb: ''
				}
				this.guige[idx].list.push(t)
			},
			//添加规格
			addGuige() {
				obj = {
					title: '',
					list: []
				}
				this.guige.push(obj)
			},
			//删除规格
			delGuige(idx) {
				this.guige.splice(idx, 1)
				this.f5();
			},
			//删除规格项
			delItem(index, idx) {
				this.guige[index].list.splice(idx, 1)
				this.f5();
			},
			f5() {
				if (this.guige.length == 0) { //如果没有规格
					return this.\$alert('您并未添加规格!无法生成表格', '提示', {
						confirmButtonText: '确定',
					});
				}
				let arr = []
				this.guige.forEach(item => { //获取规格项list, 以便于笛卡尔积计算
					arr.push(item.list)
				})
				var title = []
				this.guige.forEach(item => { //获取规格的名字.
					title.push(item.title)
				})

				let test = title.every((item) => { //如果有规格没填写.
					if (item) {
						return item
					}
				})

				let test2 = true
				arr.forEach(item => { //如果有规格项没填写.
					item.forEach(v => {
						if (!v.name) {
							test2 = false;
						}
					})
				})
				if (!test || !test2) { //则return
					return this.\$alert('您有未填项!无法生成表格', '提示', {
						confirmButtonText: '确定',
					});
				}

				// last为上次运算的结果，current为数组中的当前元素
				var duowei_arr = arr.reduce((last, current) => { //笛卡尔积计算方式. 返回的是数租
					const array = [];
					last.forEach(par1 => {
						current.forEach(par2 => {
							let ar = []
							ar.push(par1, par2)

							array.push(ar);
						});
					});
					return array;
				});
				//  duowei_arr = duowei_arr.map(item => { //把每一项的字符串,分割成数组.
				// 	return item.split('|')
				// })
				let obj = []
				duowei_arr.forEach((item, index) => {
					var test = new Object(); //创建一个新对象.
					if (!item.length) {//属性变动需要改
						let txt = {
							a: {
								name: '12'
							},
							b: {
								name: ''
							},
							c: {
								name: ''
							},
							d: {
								name: ''
							},
						}
						let name1 = title[0]
						test[name1] = item
						Object.assign(test, txt)
						obj.push(test)
					} else {
						item.forEach((v, k) => {
							var name = title[k]
							test[name] = v
						})//属性变动需要改
						let txt = { //为什么不写在外面? 因为vue的数据会自动生成一个depid, 声明在里边 每次循环的时候 都重新生成了id
							a: {
								name: '12'
							},
							b: {
								name: ''
							},
							c: {
								name: ''
							},
							d: {
								name: ''
							},
						}
						Object.assign(test, txt)
						obj.push(test)
					}
				})
				this.tableData = obj
			},
			
			GetRequest() {
				var url = location.search; //获取url中"?"符后的字串
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
					}
				}
				this.goods_id = theRequest.goods_id
				axios.post('/admin/goods/skus/edit', {
					goods_id: theRequest.goods_id
				}).then(res => {
					if (res.data.data.spec) {
						this.tableData = res.data.data.sku
						this.guige = res.data.data.spec
					}

				})
			
			}
		},
		created() {

			this.GetRequest()
		}
	})
EOF;
        $root = $request->root();
        Admin::script($vue);
        return $content
            ->header('规格')
            ->description('设置')
            ->body(view('admin.custom.skus', compact(['root'])));
    }

    /*
     * sku 生成
     */
    public function skus(Request $request)
    {
        return DB::transaction(function () use ($request) {

            // 商品信息
            $goods = Product::find($request->goods_id);
            if (!$goods) {
                return $this->responseFailed('参数错误');
            }
            if ($goods->status) {
                return $this->responseFailed('上架，无法修改规格属性');
            }
            $goods->sku = serialize($request->sku);
            $goods->spec = serialize($request->spec);
            $goods->save();

            // 删除操作
            ProductSku::where(['product_id'=>$goods->id])->delete(); // sku
            ProductSpec::where(['product_id'=>$request->goods_id])->delete(); // 规格
            ProductSpecItem::where(['product_id'=>$request->goods_id])->delete(); // 属性
            // 生成sku
            foreach ($request->sku as $item) {
                $count = count($item);
                $name = [];
                $specs = [];
                $temps = array_slice($item, 0, $count - 4);//属性变动需要改
                //print_r($temps);die();
                foreach ($temps as $key => $spec) {
                    $goods_spec = ProductSpec::where([
                        'product_id' => $goods->id,
                        'name' => $key,
                    ])->first();
                    if (!$goods_spec) {
                        $goods_spec = new ProductSpec();
                    }
                    $goods_spec->product_id = $goods->id;
                    $goods_spec->name = $key;
                    $goods_spec->save();
                    // 属性
                    $goods_spec_item = ProductSpecItem::where([
                        'product_id' => $goods->id,
                        'spec_id' => $goods_spec->id,
                        'name' => $spec['name'],
                    ])->first();
                    if (!$goods_spec_item) {
                        $goods_spec_item = new ProductSpecItem();
                    }
                    $goods_spec_item->product_id = $goods->id;
                    $goods_spec_item->spec_id = $goods_spec->id;
                    $goods_spec_item->name = $spec['name'];
                    $goods_spec_item->thumb = $spec['thumb'];
                    $goods_spec_item->save();

                    array_push($name, $goods_spec_item->name);
                    array_push($specs, $goods_spec_item->id);
                }
                $sku = new ProductSku();
                $sku->category_id = $goods->category_id;
                $sku->product_id = $goods->id;
                $sku->name = implode('+', $name);
                $sku->specs = implode('_', $specs);
                $sku->stock = $item['a']['name'];
                $sku->price = $item['b']['name']?:0;
                $sku->vip_price = $item['c']['name']?:0;
                $sku->EMGcode = $item['d']['name']?:0; //属性变动需要改，要给新增的属性赋值
                $sku->save();
            }

            // 属性序列化
            $goods_spec = ProductSpec::where([
                'product_id' => $goods->id
            ])->get();
            foreach ($goods_spec as $item) {
                $goods_spec_item = ProductSpecItem::where([
                    'product_id' => $goods->id,
                    'spec_id' => $item->id,
                ])->get(['id', 'product_id', 'spec_id', 'name', 'thumb']);
                ProductSpec::where([
                    'product_id' => $goods->id,
                    'id' => $item->id,
                ])->update(['content'=>serialize($goods_spec_item->toArray())]);
            }
            //更新商品表的最低价格
            $sku = ProductSku::getSkuMinPrice($goods->id);
            if ($sku) {
                $product = Product::find($goods->id);
                $product->price = $sku['price'];
                $product->vip_price = $sku['vip_price'];
                //$product->vip_score = $sku['vip_score'];
                $product->save();
            }
            return $this->responseSuccess('保存成功');
        }, 5);
    }

    /*
     * sku 编辑
     */
    public function skusEdit(Request $request)
    {
        // 商品信息
        $list = Product::find($request->goods_id, ['id', 'sku', 'spec']);
        if (!$list) {
            return $this->responseFailed('参数错误');
        }
        $list = $list->toArray();
        $emgCode = $list['sku'][0]['d']['name'];
        $sku = ProductSku::where('EMGcode', $emgCode)->first();
        if($sku){
            $list['sku'][0]['a']['name'] = $sku['stock'];
        }
        $emgCode = $list['sku'][1]['d']['name'];
        $sku = ProductSku::where('EMGcode', $emgCode)->first();
        if($sku){
            $list['sku'][1]['a']['name'] = $sku['stock'];
        }
        return $this->responseData($list);
    }
}
